"""
工作区服务层
"""
import logging
import uuid
from datetime import datetime
from typing import List, Dict, Optional, Any
from sqlalchemy.orm import Session
from sqlalchemy import desc, and_

from database import db_manager
from models import Workspace, AnalysisSession, Conversation, UserConfig

logger = logging.getLogger(__name__)

class WorkspaceService:
    """工作区服务"""
    
    def create_workspace(self, name: str, description: str = None, settings: Dict = None) -> Dict:
        """创建新工作区"""
        try:
            with db_manager.get_session() as session:
                workspace = Workspace(
                    name=name,
                    description=description,
                    settings=settings or {}
                )
                session.add(workspace)
                session.flush()  # 获取ID
                
                logger.info(f"创建工作区成功: {workspace.name} ({workspace.id})")
                return workspace.to_dict()
                
        except Exception as e:
            logger.error(f"创建工作区失败: {e}")
            raise
    
    def get_workspaces(self, active_only: bool = True) -> List[Dict]:
        """获取工作区列表"""
        try:
            with db_manager.get_session() as session:
                query = session.query(Workspace)
                if active_only:
                    query = query.filter(Workspace.is_active == True)
                
                workspaces = query.order_by(desc(Workspace.updated_at)).all()
                results = [ws.to_dict() for ws in workspaces]
                # 简要日志：加载到的工作区数量
                logger.info(f"加载持久化工作区: {len(results)} 个")
                return results
                
        except Exception as e:
            logger.error(f"获取工作区列表失败: {e}")
            raise
    
    def get_workspace(self, workspace_id: str) -> Optional[Dict]:
        """获取指定工作区"""
        try:
            with db_manager.get_session() as session:
                workspace = session.query(Workspace).filter(
                    Workspace.id == workspace_id,
                    Workspace.is_active == True
                ).first()
                
                if workspace:
                    return workspace.to_dict()
                return None
                
        except Exception as e:
            logger.error(f"获取工作区失败: {e}")
            raise
    
    def update_workspace(self, workspace_id: str, name: str = None, 
                        description: str = None, settings: Dict = None) -> Dict:
        """更新工作区"""
        try:
            with db_manager.get_session() as session:
                workspace = session.query(Workspace).filter(
                    Workspace.id == workspace_id
                ).first()
                
                if not workspace:
                    raise ValueError(f"工作区不存在: {workspace_id}")
                
                if name is not None:
                    workspace.name = name
                if description is not None:
                    workspace.description = description
                if settings is not None:
                    workspace.settings = settings
                
                workspace.updated_at = datetime.utcnow()
                
                logger.info(f"更新工作区成功: {workspace.name}")
                return workspace.to_dict()
                
        except Exception as e:
            logger.error(f"更新工作区失败: {e}")
            raise
    
    def delete_workspace(self, workspace_id: str) -> bool:
        """删除工作区（软删除）"""
        try:
            with db_manager.get_session() as session:
                workspace = session.query(Workspace).filter(
                    Workspace.id == workspace_id
                ).first()
                
                if not workspace:
                    raise ValueError(f"工作区不存在: {workspace_id}")
                
                workspace.is_active = False
                workspace.updated_at = datetime.utcnow()
                
                logger.info(f"删除工作区成功: {workspace.name}")
                return True
                
        except Exception as e:
            logger.error(f"删除工作区失败: {e}")
            raise
    
    def _create_default_configs(self, session: Session, workspace_id: uuid.UUID):
        """创建默认配置"""
        # 默认规则配置
        default_rules = {
            "component_categories": {
                "framework": ["bmc_core", "bmc_network", "bmc_web", "bmc_api"],
                "hardware": ["network_adapter", "general_hardware", "storage_controller", "power_supply"],
                "software": ["application", "service", "daemon"],
                "system": ["kernel", "systemd", "init"]
            },
            "error_categories": {
                "memory_error": ["memory|RAM|DDR|out of memory|OOM|segmentation fault", "内存|内存不足|内存泄漏|内存溢出"],
                "pcie_error": ["PCIe|PCI|card|adapter|device not found|link down", "PCIe卡|PCI设备|设备未找到|链路断开"],
                "network_error": ["network|connection|timeout|link down|port|interface", "网络|连接|超时|端口|接口"],
                "storage_error": ["disk|storage|I/O|read|write|sector|bad block", "磁盘|存储|I/O|读写|扇区|坏块"],
                "code_error": ["null pointer|exception|error|failed|invalid|corrupt", "空指针|异常|错误|失败|无效|损坏"],
                "permission_error": ["permission|access denied|unauthorized|forbidden", "权限|拒绝访问|未授权|禁止"]
            }
        }
        
        rules_config = UserConfig(
            workspace_id=workspace_id,
            config_type='rules',
            config_data=default_rules
        )
        session.add(rules_config)
        
        # 默认AI配置
        default_ai_config = {
            "provider": "local",
            "api_key": "",
            "model": "google/gemma-3-4b",
            "max_tokens": -1,
            "temperature": 0.7,
            "base_url": "http://localhost:1234",
            "system_prompt": "你是一个专业的日志分析专家，专门帮助用户分析系统日志中的问题。",
            "analysis_prompts": {
                "initial_analysis": "请分析以下日志数据，识别主要问题...",
                "error_analysis": "分析以下错误日志...",
                "component_analysis": "分析以下组件日志..."
            }
        }
        
        ai_config = UserConfig(
            workspace_id=workspace_id,
            config_type='ai_config',
            config_data=default_ai_config
        )
        session.add(ai_config)

class AnalysisSessionService:
    """分析会话服务"""
    
    def create_session(self, workspace_id: str, name: str, description: str = None) -> Dict:
        """创建新的分析会话"""
        try:
            with db_manager.get_session() as session:
                analysis_session = AnalysisSession(
                    workspace_id=workspace_id,
                    name=name,
                    description=description,
                    status='created'
                )
                session.add(analysis_session)
                session.flush()
                
                logger.info(f"创建分析会话成功: {analysis_session.name} ({analysis_session.id})")
                return analysis_session.to_dict()
                
        except Exception as e:
            logger.error(f"创建分析会话失败: {e}")
            raise
    
    def get_sessions(self, workspace_id: str = None, limit: int = 50) -> List[Dict]:
        """获取分析会话列表"""
        try:
            with db_manager.get_session() as session:
                query = session.query(AnalysisSession)
                if workspace_id:
                    query = query.filter(AnalysisSession.workspace_id == workspace_id)
                
                sessions = query.order_by(desc(AnalysisSession.updated_at)).limit(limit).all()
                results = [s.to_dict() for s in sessions]
                # 简要日志：加载到的会话数量
                logger.info(
                    f"加载持久化会话: {len(results)} 个" + (f"，工作区={workspace_id}" if workspace_id else "")
                )
                return results
                
        except Exception as e:
            logger.error(f"获取分析会话列表失败: {e}")
            raise
    
    def get_session(self, session_id: str) -> Optional[Dict]:
        """获取指定分析会话"""
        try:
            with db_manager.get_session() as session:
                analysis_session = session.query(AnalysisSession).filter(
                    AnalysisSession.id == session_id
                ).first()
                
                if analysis_session:
                    return analysis_session.to_dict()
                return None
                
        except Exception as e:
            logger.error(f"获取分析会话失败: {e}")
            raise
    
    def update_session(self, session_id: str, **kwargs) -> Dict:
        """更新分析会话"""
        try:
            with db_manager.get_session() as session:
                analysis_session = session.query(AnalysisSession).filter(
                    AnalysisSession.id == session_id
                ).first()
                
                if not analysis_session:
                    raise ValueError(f"分析会话不存在: {session_id}")
                
                # 更新允许的字段
                allowed_fields = ['name', 'description', 'status', 'analysis_results', 
                                'ai_analysis', 'tags', 'bookmarks', 'notes',
                                'original_filename', 'file_size', 'file_hash', 'storage_path']
                
                for field, value in kwargs.items():
                    if field in allowed_fields and hasattr(analysis_session, field):
                        setattr(analysis_session, field, value)
                
                analysis_session.updated_at = datetime.utcnow()
                
                logger.info(f"更新分析会话成功: {analysis_session.name}")
                return analysis_session.to_dict()
                
        except Exception as e:
            logger.error(f"更新分析会话失败: {e}")
            raise
    
    def delete_session(self, session_id: str) -> bool:
        """删除分析会话"""
        try:
            with db_manager.get_session() as session:
                analysis_session = session.query(AnalysisSession).filter(
                    AnalysisSession.id == session_id
                ).first()
                
                if not analysis_session:
                    raise ValueError(f"分析会话不存在: {session_id}")
                
                session.delete(analysis_session)
                
                logger.info(f"删除分析会话成功: {analysis_session.name}")
                return True
                
        except Exception as e:
            logger.error(f"删除分析会话失败: {e}")
            raise

class ConversationService:
    """对话服务"""
    
    def add_message(self, session_id: str, message_type: str, content: str, context: Dict = None) -> Dict:
        """添加对话消息"""
        try:
            with db_manager.get_session() as session:
                conversation = Conversation(
                    session_id=session_id,
                    message_type=message_type,
                    content=content,
                    context=context or {}
                )
                session.add(conversation)
                session.flush()
                
                return conversation.to_dict()
                
        except Exception as e:
            logger.error(f"添加对话消息失败: {e}")
            raise
    
    def get_conversation_history(self, session_id: str, limit: int = 100) -> List[Dict]:
        """获取对话历史"""
        try:
            with db_manager.get_session() as session:
                conversations = session.query(Conversation).filter(
                    Conversation.session_id == session_id
                ).order_by(Conversation.timestamp).limit(limit).all()
                results = [c.to_dict() for c in conversations]
                # 简要日志：加载到的对话条数
                logger.info(f"加载持久化对话: {len(results)} 条，会话ID={session_id}")
                return results
                
        except Exception as e:
            logger.error(f"获取对话历史失败: {e}")
            raise
    
    def clear_conversation_history(self, session_id: str) -> bool:
        """清空对话历史"""
        try:
            with db_manager.get_session() as session:
                session.query(Conversation).filter(
                    Conversation.session_id == session_id
                ).delete()
                
                logger.info(f"清空对话历史成功: {session_id}")
                return True
                
        except Exception as e:
            logger.error(f"清空对话历史失败: {e}")
            raise

# 服务实例
workspace_service = WorkspaceService()
session_service = AnalysisSessionService()
conversation_service = ConversationService()
